Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [1]:
# Load pickled data
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
import cv2

# Visualizations will be shown in the notebook.
%matplotlib inline

# TODO: Fill this in based on where you saved the training and testing data
# Load Trining Data and safe it

training_file = './Training_Set/train.p'
validation_file= './Training_Set/valid.p'
testing_file = './Training_Set/test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

print(len(X_train), X_train.shape)
print(len(X_valid), X_valid.shape)
print(len(X_test), X_test.shape)
34799 (34799, 32, 32, 3)
4410 (4410, 32, 32, 3)
12630 (12630, 32, 32, 3)

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [2]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results

# TODO: Number of training examples
n_train = X_train.shape[0]

# TODO: Number of testing examples.
n_test = X_test.shape[0]

# TODO: Number of validation examples.
n_valid = X_valid.shape[0]

# TODO: What's the shape of an traffic sign image?
image_shape = X_train.shape[1:3]

# TODO: How many unique classes/labels there are in the dataset.
class_names = pd.read_csv('signnames.csv', index_col=0)
n_classes = len(class_names)


# Print numbers of Training data, image shape and count of classes in data set
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Number of valid examples =", n_valid)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 12630
Number of valid examples = 4410
Image data shape = (32, 32)
Number of classes = 43

Load the sign names

In [3]:
sign_names = pd.read_csv("signnames.csv")
sign_names.set_index("ClassId")

sign_names.head(n=3)
Out[3]:
ClassId SignName
0 0 Speed limit (20km/h)
1 1 Speed limit (30km/h)
2 2 Speed limit (50km/h)

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [4]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.

n_columns = 7

f, ax = plt.subplots(n_classes, n_columns, figsize=(20, 120))
for c in range(n_classes):
    sample_indexes = np.where(y_train==c)[0]
    sample_list = np.random.choice(sample_indexes, size=n_columns, replace=False)
    ax[c, 1].set_title('%s, number of samples: %d' % (class_names.loc[c]['SignName'], len(sample_indexes)))
    for idx, sample in enumerate(sample_list):
        ax[c, idx].imshow(X_train[sample, :, :, :])
        ax[c, idx].set_axis_off()

# sample stats
plt.figure(figsize=(20, 5))
ax = plt.hist(y_train, bins=np.arange(0, n_classes))
plt.xlabel("Sample Count", fontdict=None, labelpad=None)
plt.ylabel("Number of Instances", fontdict=None, labelpad=None)

labels = y_train
c = Counter(labels)
print(c.items())

signal = []
count = []

for v in c.values():
    count.append([v])

for w in c.keys():
    signal.append([w])
    

plt.plot(signal,count, 'o')
plt.show()
# Visualizations will be shown in the notebook.

def maxfreq(y_train, n_class):
    counts = []
    for i in range(n_class):
        counts.append(np.sum(y_train == i))
    return max(counts)

def minfreq(y_train, n_class):
    counts = []
    for i in range(n_class):
        counts.append(np.sum(y_train == i))
    return min(counts)

def sumfreq(y_train, n_class):
    counts = []
    for i in range(n_class):
        counts.append(np.sum(y_train == i))
    return sum(counts)

maxf = maxfreq(y_train, 43) 
minf = minfreq(y_train, 43) 
gap = maxf - minf
## UPPERLIMIT = gap
UPPERLIMIT = maxf
sumfreq = sumfreq(y_train, 43)

print('max freq    = ', maxf)
print('min freq    = ', minf)
print ('upperlimit = ', UPPERLIMIT)
print('sum of all frequencies = ', sumfreq)

training_mean = (sumfreq/n_classes)  ## --> get the mean count
print('mean        = ', training_mean)

maxperturb = UPPERLIMIT // minf 
print('max perturbations required = ', maxperturb)
dict_items([(41, 210), (31, 690), (36, 330), (26, 540), (23, 450), (1, 1980), (40, 300), (22, 330), (37, 180), (16, 360), (3, 1260), (19, 180), (4, 1770), (11, 1170), (42, 210), (0, 180), (32, 210), (27, 210), (29, 240), (24, 240), (9, 1320), (5, 1650), (38, 1860), (8, 1260), (10, 1800), (35, 1080), (34, 360), (18, 1080), (6, 360), (13, 1920), (7, 1290), (30, 390), (39, 270), (21, 270), (20, 300), (33, 599), (28, 480), (12, 1890), (14, 690), (15, 540), (17, 990), (2, 2010), (25, 1350)])
max freq    =  2010
min freq    =  180
upperlimit =  2010
sum of all frequencies =  34799
mean        =  809.279069767
max perturbations required =  11
In [5]:
#This plot does the same as the plot before but the visualization is easier
def display_data(y_train, n_class):
    counts = []
    for i in range(n_class):
        counts.append(np.sum(y_train == i))
    plt.bar(range(43),counts)
    plt.xlabel("Sample Count", fontdict=None, labelpad=None)
    plt.ylabel("Number of Instances", fontdict=None, labelpad=None)
    
print('The data shown before augmentation...')    
display_data(y_train, 43)
The data shown before augmentation...
In [6]:
## Note:  allspace  = whitespace + bar_space
bar_space = sumfreq
allspace = maxf * n_classes 
whitespace = allspace - bar_space
print('allspace   = ', allspace)
print('bar_space  = ', bar_space)
print('whitespace = ', whitespace)
allspace   =  86430
bar_space  =  34799
whitespace =  51631
In [7]:
### Oversampling to increase the underrepresented class labels.
# Use RandomOverSampler to create a consistant data set

from imblearn.over_sampling import RandomOverSampler

dataset_size = len(X_train)
X_train = X_train.reshape(dataset_size,-2)
print(X_train.shape)
print(X_train[0].shape)
ros = RandomOverSampler()
X_resampled,y_resampled = ros.fit_sample(X_train,y_train)
print(X_resampled.shape)
print(y_resampled.shape)
dataset_size = len(X_train)
X_train = np.reshape(X_resampled,(86430,32,32,3))
y_train = y_resampled
print(X_train.shape)
print(X_train[0].shape)
/opt/conda/lib/python3.6/site-packages/sklearn/externals/six.py:31: DeprecationWarning: The module is deprecated in version 0.21 and will be removed in version 0.23 since we've dropped support for Python 2.7. Please rely on the official version of six (https://pypi.org/project/six/).
  "(https://pypi.org/project/six/).", DeprecationWarning)
(34799, 3072)
(3072,)
(86430, 3072)
(86430,)
(86430, 32, 32, 3)
(32, 32, 3)
In [8]:
# Display the oversampled datapoints

print('The data shown after over sampling...')    
display_data(y_train, 43)
The data shown after over sampling...
In [9]:
# Just plot some images to check

plt.subplot(221)
plt.imshow(X_train[50000])

plt.subplot(222)
plt.imshow(X_train[60000])

plt.subplot(223)
plt.imshow(X_train[70000])

plt.subplot(224)
plt.imshow(X_train[80000])
Out[9]:
<matplotlib.image.AxesImage at 0x7f976cc1bcc0>
In [10]:
# The equilize function prepares the image with a Color filter for further use

def equalize_hist(img):    
    img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
    
    # equalize the histogram of the Y channel only
    img_yuv[:,:,0] = cv2.equalizeHist(np.array(img_yuv[:,:,0]).astype(np.uint8))
    
    #apply contrast limited adaptive histogram equalization
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
    img_yuv[:,:,0] = clahe.apply(img_yuv[:,:,0])
    img_yuv = cv2.cvtColor(img_yuv, cv2.COLOR_YUV2BGR)
    return img_yuv


def equalize_data(data): 
    print("Equalizing...")
    for i in range(len(data)):
        data[i] = equalize_hist(np.array(data[i]))
        
    return data
In [11]:
# All three sets of data are prepared with the equlize function to feed into the network

img_bef_hist = np.copy(X_test[1])

#histogram equalization on all data
X_train = equalize_data(X_train)
X_valid = equalize_data(X_valid)
X_test = equalize_data(X_test)        

img_after_hist = X_test[1]

f, axarr = plt.subplots(1, 2, figsize=(5,5))
plt.figure()
f.subplots_adjust(hspace = .4, wspace=.001)
subtitle1 = "Before Equalization"
axarr[0].set_title(subtitle1, fontsize=10)
axarr[0].set_aspect(aspect=1, adjustable='box')
axarr[0].imshow(img_bef_hist)
subtitle2 = "After Equalization"
axarr[1].set_title(subtitle2, fontsize=10)
axarr[1].set_aspect(aspect=1, adjustable='box')
axarr[1].imshow(np.round(img_after_hist).astype(np.uint8))

plt.savefig('hist_compare.png', bbox_inches='tight')

#sort training set after data equlization for visualization
sorted_indices = np.argsort(y_test)
y_test = y_test[sorted_indices]
X_test = X_test[sorted_indices]
u, indices, freq = np.unique(y_test, return_index=True, return_counts=True)
sorted_indices = np.argsort(u)
u = u[sorted_indices]
indices = indices[sorted_indices]
freq = freq[sorted_indices]
Equalizing...
Equalizing...
Equalizing...
<matplotlib.figure.Figure at 0x7f976cbd4748>
In [12]:
# This block just prints all the data equalized to check if it worked
n_columns = 7

f, ax = plt.subplots(n_classes, n_columns, figsize=(20, 120))
for c in range(n_classes):
    sample_indexes = np.where(y_train==c)[0]
    sample_list = np.random.choice(sample_indexes, size=n_columns, replace=False)
    ax[c, 1].set_title('%s, number of samples: %d' % (class_names.loc[c]['SignName'], len(sample_indexes)))
    for idx, sample in enumerate(sample_list):
        ax[c, idx].imshow(X_train[sample, :, :, :])
        ax[c, idx].set_axis_off()

# sample stats
plt.figure(figsize=(20, 5))
ax = plt.hist(y_train, bins=np.arange(0, n_classes))

labels = y_train
c = Counter(labels)
print(c.items())
dict_items([(41, 2010), (31, 2010), (36, 2010), (26, 2010), (23, 2010), (1, 2010), (40, 2010), (22, 2010), (37, 2010), (16, 2010), (3, 2010), (19, 2010), (4, 2010), (11, 2010), (42, 2010), (0, 2010), (32, 2010), (27, 2010), (29, 2010), (24, 2010), (9, 2010), (5, 2010), (38, 2010), (8, 2010), (10, 2010), (35, 2010), (34, 2010), (18, 2010), (6, 2010), (13, 2010), (7, 2010), (30, 2010), (39, 2010), (21, 2010), (20, 2010), (33, 2010), (28, 2010), (12, 2010), (14, 2010), (15, 2010), (17, 2010), (2, 2010), (25, 2010)])
In [13]:
# This shows the destributin of the training, validation and testing set for the classes. As seen, the training class is oversampled

bins = range(n_classes) 

fig, (ax0, ax1, ax2) = plt.subplots(ncols=3, figsize=(20, 10))

ax0.hist(y_train, bins,  histtype='stepfilled', facecolor='g')
ax0.set_title('Training Set Distribution')



# Create a histogram by providing the bin edges (unequally spaced).
ax1.hist(y_valid, bins, histtype='stepfilled', facecolor='y')
ax1.set_title('Validation Set Distribution')


# Create a histogram by providing the bin edges (unequally spaced).
ax2.hist(y_test, bins,  histtype='stepfilled', facecolor='r')
ax2.set_title('Test Set Distribution')


ax0.set_xlabel('Sample Count')
ax0.set_ylabel('Number of Instances')
ax1.set_xlabel('Sample Count')
ax1.set_ylabel('Number of Instances')
ax2.set_xlabel('Sample Count')
ax2.set_ylabel('Number of Instances')



fig.tight_layout()
plt.show()
plt.savefig('data_explore.png', bbox_inches='tight')
plt.close('all')

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

Pre-process the Data Set (normalization, grayscale, etc.)

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [14]:
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.

from sklearn.utils import shuffle

X_train, y_train = shuffle(X_train, y_train)

#normalizing data
X_train = ( X_train - np.mean(X_train) ) / np.std(X_train)
X_valid = ( X_valid - np.mean(X_valid) ) / np.std(X_valid)
X_test = ( X_test - np.mean(X_test) ) / np.std(X_test)
In [15]:
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import tensorflow as tf

EPOCHS = 50
BATCH_SIZE = 256

from tensorflow.contrib.layers import flatten

x = tf.placeholder(tf.float32, (None, 32, 32, 3))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32) 
one_hot_y = tf.one_hot(y, 43)

Model Architecture

In [16]:
### Define your architecture here.
### Feel free to use as many code cells as needed.
  
mu = 0
sigma = 0.1
factor = 3
    
def LeNet(x):
    # SOLUTION: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x6.
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean = mu, stddev = sigma))
    conv1_b = tf.Variable(tf.zeros(6))
    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID')
    conv1 = tf.nn.bias_add(conv1, conv1_b)

    # SOLUTION: Activation.
    conv1 = tf.nn.relu(conv1)

    # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros(16))
    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID')
    conv2 = tf.nn.bias_add(conv2, conv2_b)

    # SOLUTION: Activation.
    actv2 = tf.nn.relu(conv2)

    # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
    conv2 = tf.nn.max_pool(actv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # SOLUTION: Flatten. Input = 5x5x16. Output = 400.
    fc0 = flatten(conv2)

    # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
    fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(120))
    fc1 = tf.add(tf.matmul(fc0, fc1_W), fc1_b)


    # SOLUTION: Activation.
    fc1    = tf.nn.relu(fc1)

    # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
    fc2_W  = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma))
    fc2_b  = tf.Variable(tf.zeros(84))
    fc2 = tf.add(tf.matmul(fc1, fc2_W), fc2_b)


    # SOLUTION: Activation.
    fc2    = tf.nn.relu(fc2)

    # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43.
    fc3_W  = tf.Variable(tf.truncated_normal(shape=(84, 43), mean = mu, stddev = sigma))
    fc3_b  = tf.Variable(tf.zeros(43))
    lenet = tf.add(tf.matmul(fc2, fc3_W), fc3_b)
    
    return lenet

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [17]:
def print_stats(session, feature_batch, label_batch, cost, accuracy):
    """
    Print information about loss and validation accuracy
    : session: Current TensorFlow session
    : feature_batch: Batch of Numpy image data
    : label_batch: Batch of Numpy label data
    : cost: TensorFlow cost function
    : accuracy: TensorFlow accuracy function
    """
    loss = session.run(cost, feed_dict={x: feature_batch, y: label_batch, keep_prob: 1.0})
    validation_accuracy = sess.run(accuracy, feed_dict={
        x: X_valid,
        y: y_valid, 
        keep_prob: 1.0
    })
    training_accuracy = sess.run(accuracy, feed_dict={x: feature_batch, y: label_batch, keep_prob: 1.0})

    print('Loss: {:>10.4f} Validation Accuracy: {:.6f} Training Accuracy: {}'.format(loss, 
                                                                                     validation_accuracy, 
                                                                                     training_accuracy))
In [18]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
from sklearn.utils import shuffle

# y = tf.placeholder(tf.int32, (None))
# one_hot_y = tf.one_hot(y, n_classes)

rate = 0.001

logits = LeNet(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)

correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

saver = tf.train.Saver()
training_loss_history = []
validation_loss_history = []


def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset + BATCH_SIZE], y_data[offset:offset + BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train)
    
    print('Training...')
    for i in range(EPOCHS):
        X_train_0, y_train_0 = shuffle(X_train, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train_0[offset:end], y_train_0[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
            
        train_loss = sess.run(loss_operation, feed_dict={x:X_train, y:y_train})
        valid_loss = sess.run(loss_operation, feed_dict={x:X_valid, y:y_valid})
        training_loss_history.append(train_loss)
        validation_loss_history.append(valid_loss)    
        validation_accuracy = evaluate(X_valid, y_valid)
        training_accuracy = evaluate(X_train, y_train)
        print("EPOCH {} ...".format(i+1))
        print('EPOCH %3d, validation accuracy %.3f' % (i + 1, validation_accuracy))
        if validation_accuracy > 0.99:
            break;
    saver.save(sess, './lenet')
    print("Model saved")
Training...
EPOCH 1 ...
EPOCH   1, validation accuracy 0.872
EPOCH 2 ...
EPOCH   2, validation accuracy 0.927
EPOCH 3 ...
EPOCH   3, validation accuracy 0.938
EPOCH 4 ...
EPOCH   4, validation accuracy 0.933
EPOCH 5 ...
EPOCH   5, validation accuracy 0.940
EPOCH 6 ...
EPOCH   6, validation accuracy 0.919
EPOCH 7 ...
EPOCH   7, validation accuracy 0.937
EPOCH 8 ...
EPOCH   8, validation accuracy 0.938
EPOCH 9 ...
EPOCH   9, validation accuracy 0.938
EPOCH 10 ...
EPOCH  10, validation accuracy 0.945
EPOCH 11 ...
EPOCH  11, validation accuracy 0.944
EPOCH 12 ...
EPOCH  12, validation accuracy 0.934
EPOCH 13 ...
EPOCH  13, validation accuracy 0.936
EPOCH 14 ...
EPOCH  14, validation accuracy 0.943
EPOCH 15 ...
EPOCH  15, validation accuracy 0.930
EPOCH 16 ...
EPOCH  16, validation accuracy 0.946
EPOCH 17 ...
EPOCH  17, validation accuracy 0.927
EPOCH 18 ...
EPOCH  18, validation accuracy 0.954
EPOCH 19 ...
EPOCH  19, validation accuracy 0.931
EPOCH 20 ...
EPOCH  20, validation accuracy 0.936
EPOCH 21 ...
EPOCH  21, validation accuracy 0.951
EPOCH 22 ...
EPOCH  22, validation accuracy 0.954
EPOCH 23 ...
EPOCH  23, validation accuracy 0.924
EPOCH 24 ...
EPOCH  24, validation accuracy 0.943
EPOCH 25 ...
EPOCH  25, validation accuracy 0.950
EPOCH 26 ...
EPOCH  26, validation accuracy 0.937
EPOCH 27 ...
EPOCH  27, validation accuracy 0.943
EPOCH 28 ...
EPOCH  28, validation accuracy 0.942
EPOCH 29 ...
EPOCH  29, validation accuracy 0.955
EPOCH 30 ...
EPOCH  30, validation accuracy 0.936
EPOCH 31 ...
EPOCH  31, validation accuracy 0.951
EPOCH 32 ...
EPOCH  32, validation accuracy 0.948
EPOCH 33 ...
EPOCH  33, validation accuracy 0.929
EPOCH 34 ...
EPOCH  34, validation accuracy 0.954
EPOCH 35 ...
EPOCH  35, validation accuracy 0.948
EPOCH 36 ...
EPOCH  36, validation accuracy 0.935
EPOCH 37 ...
EPOCH  37, validation accuracy 0.943
EPOCH 38 ...
EPOCH  38, validation accuracy 0.939
EPOCH 39 ...
EPOCH  39, validation accuracy 0.940
EPOCH 40 ...
EPOCH  40, validation accuracy 0.949
EPOCH 41 ...
EPOCH  41, validation accuracy 0.954
EPOCH 42 ...
EPOCH  42, validation accuracy 0.955
EPOCH 43 ...
EPOCH  43, validation accuracy 0.956
EPOCH 44 ...
EPOCH  44, validation accuracy 0.956
EPOCH 45 ...
EPOCH  45, validation accuracy 0.955
EPOCH 46 ...
EPOCH  46, validation accuracy 0.955
EPOCH 47 ...
EPOCH  47, validation accuracy 0.955
EPOCH 48 ...
EPOCH  48, validation accuracy 0.955
EPOCH 49 ...
EPOCH  49, validation accuracy 0.955
EPOCH 50 ...
EPOCH  50, validation accuracy 0.955
Model saved
In [19]:
loss_plot = plt.subplot(2,1,1)
loss_plot.set_title('Loss')
loss_plot.plot(training_loss_history, 'r', label='Training Loss')
loss_plot.plot(validation_loss_history, 'b', label='Validation Loss')
loss_plot.set_xlim([0, EPOCHS])
loss_plot.legend(loc=4)
Out[19]:
<matplotlib.legend.Legend at 0x7f9707113a90>
In [20]:
with tf.Session() as sess:
    # Restore variables from disk.
    saver.restore(sess, './lenet')

    # evaluate on training set
    training_accuracy = evaluate(X_train, y_train)
    print('Model accuracy on training set = %.3f' % training_accuracy)
    print()
    # evaluate on test set
    valid_accuracy = evaluate(X_valid, y_valid)
    print('Model accuracy on validation set = %.3f' % valid_accuracy)
    print()
    test_accuracy = evaluate(X_test, y_test)
    print('Model accuracy on test set = %.3f' % test_accuracy)
    print()
INFO:tensorflow:Restoring parameters from ./lenet
Model accuracy on training set = 1.000

Model accuracy on validation set = 0.955

Model accuracy on test set = 0.947


Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [21]:
# Import the image set and set the labes.

import cv2
import os

test_table = pd.read_csv('images/gt.csv')
n_test_samples = len(test_table)
X_test_2 = np.zeros((n_test_samples, 32, 32, 3), dtype=np.uint8)
y_test_2 = test_table['ClassId'].values.astype(np.uint8)

f, ax = plt.subplots(n_test_samples, 1, figsize=(20, 120))

for idx, row in test_table.iterrows():
    img_original = cv2.cvtColor(cv2.imread(os.path.join('images', row['File']), cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB) 
    ax[idx].imshow(img_original)
    ax[idx].set_axis_off()
    ax[idx].set_title(class_names.loc[row['ClassId']]['SignName'])
    img_resized = cv2.resize(img_original, (32, 32))
    X_test_2[idx, :, :, :] = img_resized
    
print(y_test_2)
[14  4  4 14 14 14 14 28 28 28 28  1 13 18  1 14 14  7 15  5 39 39 14]
In [22]:
# Process the imported images and normalize the images for prediction function

X_train_new_p = equalize_data(X_test_2)
X_train_new_p = (X_train_new_p - np.mean(X_train_new_p) ) / np.std(X_train_new_p)
Equalizing...

Predict the Sign Type for Each Image

In [23]:
# This is the prediction function. It uses the given images and predicts fromthe lenet the image

predictions = tf.argmax(logits, 1)

def predict_on_custom_data(X_data):
    sess = tf.get_default_session()
    pred = sess.run(predictions, feed_dict={x:X_data})
    return pred 
In [24]:
# The answer to the prediction is given from the trained model

with tf.Session() as sess:
    saver.restore(sess, './lenet')

    predictions = predict_on_custom_data(X_train_new_p)
    print(predictions)
    
    for idx, pred, actual in zip(range(len(predictions)), predictions, y_test_2):
        if pred==actual:
            print('%s: correctly identified "%s"' % (test_table.loc[idx]['File'], class_names.loc[pred]['SignName']))
        else:
            print('%s: ERROR detected "%s", actual "%s"' % (test_table.loc[idx]['File'], class_names.loc[pred]['SignName'], class_names.loc[actual]['SignName']))
INFO:tensorflow:Restoring parameters from ./lenet
[14  4  4 14 14 14 14  7 28 28 28 39 13 18 11 12 14  5  8  1 37 39 14]
001.png: correctly identified "Stop"
002.png: correctly identified "Speed limit (70km/h)"
003.png: correctly identified "Speed limit (70km/h)"
004.png: correctly identified "Stop"
005.png: correctly identified "Stop"
006.png: correctly identified "Stop"
007.png: correctly identified "Stop"
008.png: ERROR detected "Speed limit (100km/h)", actual "Children crossing"
009.png: correctly identified "Children crossing"
010.png: correctly identified "Children crossing"
011.png: correctly identified "Children crossing"
012.png: ERROR detected "Keep left", actual "Speed limit (30km/h)"
013.png: correctly identified "Yield"
014.png: correctly identified "General caution"
015.png: ERROR detected "Right-of-way at the next intersection", actual "Speed limit (30km/h)"
016.png: ERROR detected "Priority road", actual "Stop"
018.png: correctly identified "Stop"
020.png: ERROR detected "Speed limit (80km/h)", actual "Speed limit (100km/h)"
021.png: ERROR detected "Speed limit (120km/h)", actual "No vehicles"
026.png: ERROR detected "Speed limit (30km/h)", actual "Speed limit (80km/h)"
028.png: ERROR detected "Go straight or left", actual "Keep left"
029.png: correctly identified "Keep left"
032.png: correctly identified "Stop"

Analyze Performance

In [25]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.

with tf.Session() as sess:
    # Restore variables from disk.
    saver.restore(sess, './lenet')

    # evaluate on test set
    test_2_accuracy = evaluate(X_train_new_p, y_test_2)
    print('Model accuracy on a custom test set = %.3f' % test_2_accuracy)
INFO:tensorflow:Restoring parameters from ./lenet
Model accuracy on a custom test set = 0.652

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [30]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.

from pylab import rcParams
top_5 = tf.nn.top_k(tf.nn.softmax(logits), k=5)

rcParams['figure.figsize'] = 25, 30

f, axarr = plt.subplots(5, 2)
f.subplots_adjust(bottom=0.00)

top_k = 5


with tf.Session() as sess:
    # Restore variables from disk.
    saver.restore(sess, './lenet')

    # evaluate on test set
    
    test_2_top_5 = sess.run(top_5, feed_dict={x: X_train_new_p})
    
    # print out
    for idx in range(len(test_2_top_5.values)):
        print('%s' % class_names.loc[y_test_2[idx]]['SignName'])
        for sample in range(len(test_2_top_5.values[idx])):
            print('  %.5f %s' % (test_2_top_5.values[idx, sample], class_names.loc[test_2_top_5.indices[idx, sample]]['SignName']))
        
INFO:tensorflow:Restoring parameters from ./lenet
Stop
  0.92765 Stop
  0.06933 No vehicles
  0.00292 Yield
  0.00004 No passing
  0.00003 Keep right
Speed limit (70km/h)
  1.00000 Speed limit (70km/h)
  0.00000 Speed limit (30km/h)
  0.00000 Speed limit (20km/h)
  0.00000 Traffic signals
  0.00000 Road narrows on the right
Speed limit (70km/h)
  0.99978 Speed limit (70km/h)
  0.00022 Speed limit (20km/h)
  0.00000 Speed limit (30km/h)
  0.00000 Speed limit (120km/h)
  0.00000 Speed limit (80km/h)
Stop
  1.00000 Stop
  0.00000 No vehicles
  0.00000 Yield
  0.00000 Keep right
  0.00000 Turn right ahead
Stop
  0.99999 Stop
  0.00001 No entry
  0.00000 No passing
  0.00000 Speed limit (120km/h)
  0.00000 No vehicles
Stop
  1.00000 Stop
  0.00000 No entry
  0.00000 No passing
  0.00000 Priority road
  0.00000 No vehicles
Stop
  1.00000 Stop
  0.00000 No entry
  0.00000 Wild animals crossing
  0.00000 No vehicles
  0.00000 Speed limit (20km/h)
Children crossing
  0.72462 Speed limit (100km/h)
  0.19850 Pedestrians
  0.06553 Roundabout mandatory
  0.00986 Children crossing
  0.00040 Right-of-way at the next intersection
Children crossing
  1.00000 Children crossing
  0.00000 Right-of-way at the next intersection
  0.00000 End of no passing
  0.00000 Beware of ice/snow
  0.00000 Speed limit (80km/h)
Children crossing
  0.65970 Children crossing
  0.27172 Right-of-way at the next intersection
  0.03828 Dangerous curve to the right
  0.02667 Road work
  0.00234 Speed limit (80km/h)
Children crossing
  1.00000 Children crossing
  0.00000 End of no passing
  0.00000 Right-of-way at the next intersection
  0.00000 End of all speed and passing limits
  0.00000 Beware of ice/snow
Speed limit (30km/h)
  0.86393 Keep left
  0.05394 No passing
  0.03840 Bumpy road
  0.02944 Go straight or left
  0.01122 Speed limit (50km/h)
Yield
  0.99997 Yield
  0.00003 Speed limit (30km/h)
  0.00000 Keep right
  0.00000 No entry
  0.00000 No passing for vehicles over 3.5 metric tons
General caution
  1.00000 General caution
  0.00000 Traffic signals
  0.00000 Pedestrians
  0.00000 Right-of-way at the next intersection
  0.00000 Speed limit (30km/h)
Speed limit (30km/h)
  0.95596 Right-of-way at the next intersection
  0.02639 Speed limit (30km/h)
  0.00926 Wild animals crossing
  0.00448 Speed limit (80km/h)
  0.00195 Bicycles crossing
Stop
  0.96328 Priority road
  0.03665 Stop
  0.00004 Yield
  0.00002 No passing
  0.00001 No entry
Stop
  0.92441 Stop
  0.04780 Traffic signals
  0.02039 Double curve
  0.00359 Wild animals crossing
  0.00143 Road work
Speed limit (100km/h)
  0.98465 Speed limit (80km/h)
  0.01060 Speed limit (100km/h)
  0.00206 Right-of-way at the next intersection
  0.00170 No passing
  0.00092 Road work
No vehicles
  0.49116 Speed limit (120km/h)
  0.22618 No vehicles
  0.14274 Stop
  0.12357 Bumpy road
  0.00578 Yield
Speed limit (80km/h)
  0.63279 Speed limit (30km/h)
  0.36680 Speed limit (50km/h)
  0.00033 Speed limit (80km/h)
  0.00006 Road narrows on the right
  0.00002 Speed limit (70km/h)
Keep left
  0.45141 Go straight or left
  0.23820 Speed limit (80km/h)
  0.12995 Keep right
  0.08921 Keep left
  0.04820 Roundabout mandatory
Keep left
  0.99092 Keep left
  0.00908 Go straight or left
  0.00000 Roundabout mandatory
  0.00000 Keep right
  0.00000 Turn right ahead
Stop
  0.99968 Stop
  0.00031 Speed limit (70km/h)
  0.00000 Speed limit (30km/h)
  0.00000 No passing
  0.00000 Speed limit (120km/h)
In [ ]:
 

Step 4: Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [46]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it maybe having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(15,15))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
            
            
input_img = np.zeros((1, 32, 32, 3), dtype=np.float32)
input_img[0, :, :, :] = X_test_2[3]

with tf.Session() as sess:
    # Restore variables from disk.
    saver.restore(sess, './lenet')
    outputFeatureMap(input_img, actv2)
INFO:tensorflow:Restoring parameters from ./lenet
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-46-9c532612bdfd> in <module>
     35     # Restore variables from disk.
     36     saver.restore(sess, './lenet')
---> 37     outputFeatureMap(input_img, actv2)

NameError: name 'actv2' is not defined

Question 9

Discuss how you used the visual output of your trained network's feature maps to show that it had learned to look for interesting characteristics in traffic sign images

Answer: From the feature maps it can be seen that the trained network was indeed able to learn some features of a Yield sign. Some of the feature maps seem to be noisy though (not like on NVIDIA pics).

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.